package com.sskj.linechat.utils;


import android.view.View;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sskj.common.base.App;
import com.sskj.common.util.TimeUtil;
import com.sskj.linechat.R;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SendCodeUtil {

    private static BottomSheetDialog bottomSheet;

    public static Disposable timeCount(LifecycleProvider lifecycleProvider, TextView tvGetCheckCode) {
        return TimeUtil.newTime(lifecycleProvider)
                .subscribe(aLong -> {
                    if (aLong > 0) {
                        tvGetCheckCode.setText(aLong + "s");
                    } else {
                        tvGetCheckCode.setText(App.INSTANCE.getString(R.string.libsendCodeUtil1));
                        tvGetCheckCode.setEnabled(true);
                    }
                });
    }

    public static Disposable timeCount(LifecycleProvider lifecycleProvider, TextView tvGetCheckCode, TextView tv1) {
        return TimeUtil.newTime(lifecycleProvider)
                .subscribe(aLong -> {
                    if (aLong > 0) {
                        tvGetCheckCode.setText(aLong + "s");
                        tv1.setVisibility(View.VISIBLE);
                    } else {
                        tvGetCheckCode.setText(App.INSTANCE.getString(R.string.libsendCodeUtil1));
                        tvGetCheckCode.setEnabled(true);
                        tv1.setVisibility(View.GONE);
                    }
                });
    }


    public static Disposable timeCount(LifecycleProvider lifecycleProvider, long second, TextView tvGetCheckCode, String s) {
        return newTime(lifecycleProvider, second)
                .subscribe(aLong -> {
                    if (aLong > 0) {
                        tvGetCheckCode.setText(aLong + s);
                    } else {
//                        LiveEventBus.get(RxBusCode.TIMEINFO + "").post(1);
                    }
                });
    }


    private static Flowable<Long> newTime(LifecycleProvider lifecycleProvider, long second) {
        return Flowable.intervalRange(0L, second, 0L, 1L, TimeUnit.SECONDS).onBackpressureDrop().compose(lifecycleProvider.bindUntilEvent(FragmentEvent.DESTROY)).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).map((o) -> {
            return second - 1 - (Long) o;
        });
    }
}
